

import logging
import time


import op.op_dk  as op_dk

# 汇聚信息的节点
TARGET_NODE = 0x0004

# 任务 3 : 数据传到主星

class Task4_info:
    def __init__(self):
        self.list_watchSallite = []
        self.list_calculateSallite = []

task4_info = Task4_info()

def set(list_watchSallite, list_calculateSallite):
    pass

def run():
    logging.info(">>>>")
    logging.info("Scene-2 task4 Run...")
    logging.info("<<<<")

    return True



import pymongo                                                                                                                                                             
import subprocess
import time
    
# MongoDB(中科大) 数据库连接信息
uri = "mongodb://admin:admin123@192.168.210.234:27017/"
client = pymongo.MongoClient(uri)
# 选择数据库和集合 
mongo_db = client.sat_test_20230424testdbfsadasdfqwerr
link = mongo_db["mobile_control"]
    
        
def run_command(command):
    """运行命令并返回输出"""
    result = subprocess.run(command, capture_output=True, text=True, shell=True)
    if result.returncode == 0:
        return result.stdout.strip()
    else:
        print(f"Error running command: {result.stderr}")
        return None
    
# 从列表id到卫星对应pod名称的格式转换
# 返回卫星对应pod名称
def get_pod_name_by_id(id):
    cursor = link.find({"nodeID":id}).limit(1)
    ip = next(cursor,None)['nodeIP']

    # 调用 Bash 脚本
    result = subprocess.run(
        f"kubectl get pods -o wide --namespace=k8s-test | grep {ip} | awk '{{print $1}}'",
        capture_output=True, text=True, shell=True)

    pod_name = result.stdout.split("\n")[0]

    return pod_name


def exec_in_pod(pod_name, container, command):                                                                                                                             
    """在指定 pod 的指定容器中执行命令"""
    cmd = f"kubectl exec -it -n k8s-test {pod_name} -c {container} -- /bin/bash -c \"{command}\""
    return run_command(cmd)


# if __name__ == "__main__":

def run():
    # print(f"id_10,name:{id2podname(10)}")
    # 获取 Pod 名称

    aid_star = [2,3,4,5]
    aid_star_str = ",".join(map(str,aid_star))

    main_pod_name = get_pod_name_by_id(1)

    for i in range(len(aid_star)):
        print(f"ID:{aid_star[i]},podName:{get_pod_name_by_id(aid_star[i])}")

    # ------------------- main pod -----------------------

    # 在主 Pod 中执行命令
    #exec_in_pod(main_pod_name, "simulation-task2", "cd /workspace/main_star_test && python calculate_main_star_dispatcher.py '6,7,8,9'")
    exec_in_pod(main_pod_name, "simulation-task2", f"cd /workspace/main_star_test && python calculate_main_star_dispatcher.py {aid_star_str}")
    print(f"main_pod_name_1: {main_pod_name}")

    # # # 等待一段时间
    time.sleep(2)

    exec_in_pod(main_pod_name, "simulation-task2", f"cd /workspace/main_star_test && python calculate_main_star_collector.py {len(aid_star)}")
    print(f"main_pod_name_2: {main_pod_name}")


    # ------------------- aid pod -----------------------
    # 输出 Pod 名称并进入 Pod 执行命令
    for i in range(len(aid_star)):
        aid_pod_name = get_pod_name_by_id(aid_star[i])
        exec_in_pod(aid_pod_name, "simulation-task2", "cd /workspace/aid_star && python calculate_aid_star_processServer.py > output.log 2>&1 &")
        print(f"aid_pod_name: {aid_pod_name};")

    print("execute successfully")
